import { createRouter, createWebHistory } from 'vue-router'
import store from '@/store'
import Login from '@/views/login'
import Main from '@/views/main'

const routes = [
  {
    path: '/',
    name: 'home',
    redirect: '/home',
    component: Main,
    children: [
      {
        path: 'home',
        name: 'home',
        meta: {
          hideInMenu: true,
          title: '首页',
          notCache: true
        },
        component: () => import('@/views/home')
      }
    ]
  },
  {
    path: '/sys',
    name: 'sys',
    component: Main,
    children: [
      {
        path: 'menu',
        name: 'sys.menu',
        meta: {
          title: '菜单管理',
          notCache: true
        },
        component: () => import('@/views/sys/menu')
      }
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: Login
  }
]

const router = createRouter({
  routes,
  history: createWebHistory(),
  scrollBehavior() {
    return { top: 0 }
  }
})
const modules = import.meta.glob('../views/**/**.vue')
function loadView(view = 'home') {
  return modules[`../views/${view}.vue`]
}
function addRoutes(menus) {
  menus.forEach((item) => {
    let { redirect } = item
    if (item.children && item.children.length > 0) {
      redirect = `${item.path}/${item.children[0].path}`
    }
    router.addRoute({
      name: item.name,
      path: item.path,
      redirect,
      component: loadView(item.view),
      children: []
    })
    if (item.children && item.children.length > 0) {
      item.children.forEach((child) => {
        router.addRoute(item.name, {
          name: child.name,
          path: child.path,
          component: loadView(child.view)
        })
      })
    }
  })
  // console.log('routes ', router.getRoutes())
}
router.beforeEach(async (to, from, next) => {
  if (to.path === '/login') {
    // 登录页放行
    next()
    return
  }
  const { token, menus } = store.state.auth
  if (!token) {
    // 没有token去登录页
    next('/login')
    return
  }

  // 获取菜单
  if (!menus || menus.length === 0) {
    const m = await store.dispatch('getMenus')
    addRoutes(m)
    console.log('routes', router.getRoutes())
    next(to.fullPath)
    return
  }

  next()
})

export default router
